﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using DataForest.DataModel;

namespace DataForest.View.Converter
{
    class NodeToStartpointConverter : Freezable, IValueConverter
    {

        private System.Windows.Controls.TreeView treeView;

        public System.Windows.Controls.TreeView TreeView
        {
            get { return (System.Windows.Controls.TreeView)GetValue(TreeViewProperty); }
            set { SetValue(TreeViewProperty, value); }
        }

        public static readonly DependencyProperty TreeViewProperty =
            DependencyProperty.Register("TreeView", typeof(System.Windows.Controls.TreeView), typeof(NodeToStartpointConverter), new PropertyMetadata(TreeViewChanged));


        private static void TreeViewChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            NodeToStartpointConverter converter = d as NodeToStartpointConverter;
            System.Windows.Controls.TreeView tree = e.NewValue as System.Windows.Controls.TreeView;

            if (tree == null || converter == null) return;

            converter.treeView = tree;
        }

        protected override Freezable CreateInstanceCore()
        {
            return new NodeToStartpointConverter();
        }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Node node = value as Node;
            if (treeView != null && node != null && node.Parent != null)
            {
                TreeViewItem item = this.FindTreeViewItem(node.Parent);
                if (item != null)
                {
                    return item.ActualWidth / 2;
                }
            }
            return 0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        private TreeViewItem FindTreeViewItem(Node node)
        {
            Stack<Node> path = new Stack<Node>();
            Node currNode = node;
            while (currNode != null)
            {
                path.Push(currNode);
                currNode = currNode.Parent;
            }

            ItemsControl items = treeView as ItemsControl;
            while (path.Count != 0)
            {
                Node find = path.Pop();
                foreach (object item in items.Items)
                {
                    if (item == find)
                    {
                        items = items.ItemContainerGenerator.ContainerFromItem(find) as ItemsControl;
                        break;
                    }
                }
            }
            return items as TreeViewItem;

        }
    }
}
